'use strict';

angular.module('xuexibangApp')
	.controller('ManageCtrl', function($scope, Exam, Auth, Klass, Util, User, $filter, $state) {
		$scope.noshare = true;
		if (Auth.isRole('teacher')) {
			$scope.isteacher = true;
		} else {
			$scope.isteacher = false;
			$scope.manageInfo = " 只有班主任和任课老师有权限管理考试成绩单。";
			return;
		}
		$scope.examid = $state.params.id;
		var me = Auth.getCurrentUser();
		$scope.klasses = [];
		$scope.selKlass = {};
		$scope.selCourses = [];
		$scope.scoreinfo = "首先选择要录入的分数课程，录入学号后四位就能锁定一名学生，回车后自动跳入分数录入框。如果三位学号已经锁定一名，可直接回车进入分数录入框。分数录入完毕，回车提交，自动进入序号录入框。";
		$scope.examentries = [];
		if ($scope.examid) {
			Exam.get({
				id: $scope.examid
			}, function(exam) {
				//console.log(exam);
				Klass.get({
					code: exam.klass
				}, function(klass) {
					ExamSchema = exam; //由于有了_id，再次保存变为update
					$scope.selKlass = klass;
					$scope.title = exam.title;
					$scope.comment = exam.comment;
					if(exam.flag&&exam.flag==1){
						$scope.noshare=false;
					}else{
						$scope.noshare=true;
					}
					$scope.createtime = exam.createtime;
					$scope.examcourses = exam.courses;
					if ($scope.examcourses.length > 1) $scope.examcourses = _.dropRight(exam.courses); //编辑旧成绩单，去掉总分,单门成绩单，无总分栏目
					$scope.scorecourse=$scope.examcourses[0];
					exam.content.forEach(function(value, key) {
						var examentry = {};
						examentry.student = value.student;
						examentry.scores = value.scores;
						if ($scope.examcourses.length > 1) examentry.scores = _.dropRight(value.scores); //编辑旧成绩单，去掉总分
						$scope.examentries.push(examentry);
					})
					$scope.showExamform = true;
					//ExamSchema.content=$scope.examentries;
					ExamSchema.creater = Auth.getCurrentUser().name;
				}, function(err) {
					console.log(err);
				})
			}, function(err) {
				console.log(err);
			})
		} else {
			if (me.klasses && me.klasses.length > 0) {
				me.klasses.forEach(function(value, key) {
					//console.log(value,key);
					Klass.get({
						code: value
					}, function(data) {
						$scope.klasses.push(data);
					})
				})
			}
		}
		$scope.selectedKlass = function(klass) {
			console.log(klass);
			$scope.selCourses = [];
			$scope.selKlass = klass;
			$scope.isSeltedAll = false;
			$scope.showExamform = false;
			var courses = me.courses;
			if (me.chargeklass && me.chargeklass === klass.code) {
				courses = Util.courses;
			}
			if (!courses) {
				$scope.isteacher = false;
				$scope.manageInfo = "只有班主任和你的任课老师有权限管理考试成绩单。你是老师，但没有授课任务。";
				console.log("不是任教老师，又没有授课");
				return;
			}
			$scope.courses = [];
			for (var i = 0; i < courses.length; i++) {
				//console.log(Util.courses[i]);
				$scope.courses.push({
					checked: false,
					code: courses[i],
					name: courses[i]
				});
			}
			if ($scope.courses.length == 1) {
				$scope.courses[0].checked = true;
				$scope.selectedCourse();
			}
		}

		$scope.selectedCourseAll = function(value) {
			console.log($scope.isSeltedAll);
			$scope.courses.forEach(function(value, key) {
				value.checked = $scope.isSeltedAll;
			})
			$scope.selCourses = Util.getChecked($scope.courses);
		}
		$scope.selectedCourse = function() {
			$scope.selCourses = Util.getChecked($scope.courses);
			console.log(Util.getChecked($scope.courses));
		}
		$scope.selectedScorescourse = function() {
			console.log($scope.scorecourse);
			console.log($scope.examcourses);
			$scope.scoreinfo = "现在录入的是：" + $scope.scorecourse + "分数";
		}
		$scope.endInputCode = function() {
			if ($scope.selectedExamentries.length == 1) {
				//$('#inputCode').blur();
				$scope.studentCode = $scope.selectedExamentries[0].student.code;
				$scope.scoreinfo = "现在录入的是：" + $scope.selectedExamentries[0].student.name + "的" + $scope.scorecourse + "分数";
				//////////////////////////////////////

				$("#inputScore").focus();
				if ($scope.studentScore) { //已经录入分数，先把分数显示出来，回车后获得焦点并选中，声音提示
					Util.beep();
					$("#inputScore").select();
				}
				/////////////////////////////
				return;
			};
			if ($scope.selectedExamentries.length > 1) {
				//$scope.scoreinfo = "学号尚未锁定一个学生，请继续录入！";
				Util.beep();
			} else {
				$scope.scoreinfo = "没有该学号，请纠正！！！！！！！！";
			}
		}
		$scope.codeChange = function(code) {
			//console.log(code, $scope.examentries);
			$scope.selectedExamentries = [];
			$scope.scoreinfo = "";
			for (var i = 0; i < $scope.examentries.length; i++) {
				//console.log(code, $scope.examentries[i].student.code, code.length > 4 ? code : $scope.selKlass.code + code);
				if ($scope.examentries[i].student.code.indexOf(code.length > 4 ? code : $scope.selKlass.code + code) > -1) {
					//console.log($scope.examentries[i].student);
					$scope.selectedExamentries.push($scope.examentries[i]);
					$scope.scoreinfo += $scope.examentries[i].student.code.substr(6) + $scope.examentries[i].student.name + " ";
				}
			}
			if ($scope.selectedExamentries.length == 1) { //学号锁定一个学生，自动切换分数录入框
				//$scope.scoreinfo="现在录入的是："+$scope.selectedExamentries[0].student.name+"的"+$scope.scorecourse+"分数";
				//$("#inputScore").focus();
				//////////////////////////////////////
				var examentriy = $scope.selectedExamentries[0]; //找到这个学生的看是否曾经录入过，已经有分数，声音提示下
				for (var i = 0; i < examentriy.scores.length; i++) {
					//console.log(examentriy.scores[i].course, $scope.scorecourse);
					if (examentriy.scores[i].course == $scope.scorecourse) {
						$scope.selectedScore = examentriy.scores[i];
						break;
					}
				}
				if ($scope.selectedScore&&$scope.selectedScore.value) {
					console.log("曾经录过分数：", $scope.selectedScore.value);
					$scope.studentScore = $scope.selectedScore.value; //已经录入分数，先把分数显示出来，回车后获得焦点并选中，声音提示
				}
				////////////////////////////////////////////
			}
			if ($scope.selectedExamentries.length < 1) {
				$("#inputCode").css("background-color", "#CC3333");
				$scope.scoreinfo = "没有该学号，请纠正！！！！！！！！";
				Util.beep();
			} else {
				$("#inputCode").css("background-color", "#FFFFFF");

			}
		}
		$scope.saveScore = function() {
			if (!$scope.scorecourse) {
				$scope.scoreinfo = "选择课程！！！！！！！！";
				Util.beep();
				return;
			}
			if ($scope.selectedExamentries.length != 1) {
				$scope.scoreinfo = "学号数据错误！";
				Util.beep();
				return;
			}
			if (!($scope.studentScore <= 150 && $scope.studentScore >= 0)) {
				$scope.scoreinfo = "分数数据错误！现在限定最大分数150，最小分数0";
				Util.beep();
				return;
			}
			var examentriy = $scope.selectedExamentries[0];
			//console.log(examentriy);
			for (var i = 0; i < examentriy.scores.length; i++) {
				//console.log(examentriy.scores[i].course, $scope.scorecourse);
				if (examentriy.scores[i].course == $scope.scorecourse) {
					$scope.selectedScore = examentriy.scores[i];
					break;
				}
			}
			if ($scope.selectedScore) {
				//console.log($scope.examentries[0]);
				//console.log($scope.selectedScore, examentriy);
				$scope.selectedScore.value = $scope.studentScore;
				//console.log($scope.selectedScore, examentriy);
			} else {
				$scope.scoreinfo = "莫名其妙的数据错误！";
				Util.beep();
				return;
			}
			$scope.selectedExamentries = [];
			$scope.studentCode = $scope.studentScore = "";
			$scope.scoreinfo = "现在录入的是：" + $scope.scorecourse + "分数";
			$("#inputCode").focus();
			//console.log("保存按钮");
		}
		$scope.saveExam = function() {
			console.log("title", $scope.title);
			if (_.isUndefined($scope.title) || $scope.title == "") {
				$scope.examinfo = "你忘记录入成绩单标题了";
				return;
			}
			if ($scope.examentries.length == 0) {
				$scope.examinfo = "本班级没有学生数据，请先维护班级学生信息。";
				return;
			}
			$scope.examinfo = "";
			ExamSchema.title = $scope.title;
			ExamSchema.comment = $scope.comment;
			if($scope.noshare){
				ExamSchema.flag=0;
			}else{
				ExamSchema.flag=1;
			}
			var examentries = angular.copy($scope.examentries);
			//考试课程一门以上，加入总分
			if (ExamSchema.courses.length > 1) {//一门以上成绩单，加入总分栏目
				if (_.last(ExamSchema.courses) != '总分') { //多次提交，防止过多加入总分科目
					ExamSchema.courses.push('总分');
				}
			}
			//计算每个考生的总分
			examentries.forEach(function(examentry, key) {
				var sum = 0;
				for (var i = 0; i < examentry.scores.length; i++) {
					examentry.scores[i].value = parseFloat(examentry.scores[i].value);//把分数转换成数字，计算总分和排序
					sum += _.isNaN(examentry.scores[i].value) ? 0 : examentry.scores[i].value;
				}
				if (ExamSchema.courses.length > 1) {//一门以上成绩单，加入总分栏目
					var score = angular.copy(ScoreSchema);
					score.course = '总分';
					score.value = sum;
					examentry.scores.push(score);
				}
			})

			//对所有课程以及总分排序，填写名次rank的值
			ExamSchema.courses.forEach(function(value, key) {
				console.log(value, key);
				examentries = $filter('orderBy')(examentries, function(examentry) {
					var scorevalue = examentry.scores[key].value;
					return _.isNaN(scorevalue) ? 0 : scorevalue;
				}, true);
				var rank = 0;
				var lastscorevalue = 100000;
				for (var i = 0; i < examentries.length; i++) {
					var score = examentries[i].scores[key];
					if (_.isNaN(score.value)) {
						break;
					}
					if (score.value < lastscorevalue) {
						rank = i + 1;
						lastscorevalue = score.value;
					}
					score.rank = rank;
					console.log(examentries[i].student.name, score.course, score.value, score.rank);
				}
			})
			ExamSchema.content = examentries;
			console.log(ExamSchema);
			//ExamSchema数据已经准备好了，开始向服务器发送
			Exam.save(ExamSchema, function(data) {
				ExamSchema = data; //由于有了_id，再次保存变为update
				$scope.examinfo = "该成绩单已经成功保存，现在可以继续生成新成绩单，或者继续编辑修改本成绩单。";
				console.log("保存成功", ExamSchema);
			}, function(err) {
				$scope.examinfo = "保存失败，请把出错信息告知管理员，进行错误定位和排除：" + err;
				console.log(err);
			})

		}
		$scope.newExam = function() {
			$scope.students = User.students({
				klass: $scope.selKlass.code
			}, function(users) {
				//console.log(users,$scope.selKlass,$scope.selCourses);
				$scope.title = "";
				$scope.examentries = [];
				var examscores = [];
				delete ExamSchema._id;
				delete ExamSchema.createtime;
				ExamSchema.klass = $scope.selKlass.code;
				$scope.examcourses = ExamSchema.courses = angular.copy($scope.selCourses);
				$scope.scorecourse=$scope.examcourses[0];
				$scope.scoreinfo="";
				for (var i = 0; i < ExamSchema.courses.length; i++) {
					var score = angular.copy(ScoreSchema);
					score.course = ExamSchema.courses[i];
					examscores.push(score);
				}
				for (var i = 0; i < users.length; i++) {
					var examentry = angular.copy(EntrySchema);
					var user = users[i];
					examentry.student.code = user.code;
					examentry.student.name = user.name;
					examentry.scores = angular.copy(examscores);
					$scope.examentries.push(examentry)
				}
				$scope.showExamform = true;
				//ExamSchema.content=$scope.examentries;
				ExamSchema.creater = Auth.getCurrentUser().name;
				//console.log($scope.examentries);
			});
			//console.log($scope.selKlass,$scope.selCourses);
		}
		$scope.tdinputNext = function(row, col) {
			//console.log(arguments, event);
			var maxrow = $scope.examentries.length - 1;
			var maxcol = $scope.examcourses.length - 1;
			//console.log(row,col,$scope.examcourses.length,$scope.examentries.length);
			var nextcol = col;
			var nextrow = row;
			var keycode = event.which;
			if (keycode == 13) { //回车
				nextcol = col + 1;
				if (nextcol > maxcol) {
					if (nextrow < maxrow) {
						nextcol = 0;
						nextrow = row + 1;
					}
				}
			} else if (keycode == 38) { //上箭头
				if (row > 0) {
					nextrow = row - 1;
				}
			} else if (keycode == 40) { //下箭头
				if (row < maxrow) {
					nextrow = row + 1;
				}
			}
			$("#td" + nextrow + nextcol).focus();
			$("#td" + nextrow + nextcol).select();
		}
	})
var ScoreSchema = {
	course: "",
	value: "",
	rank: ""
};
var EntrySchema = {
	student: {
		code: null,
		name: null
	},
	scores: []
}
var ExamSchema = {
	title: null,
	klass: null,
	courses: [],
	content: [],
	creater: null
}
